package com.spzx.channel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.spzx.channel.domain.vo.ItemVo;
import com.spzx.channel.service.ItemVoService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.JwtUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductDetails;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.vo.SkuPriceVo;
import com.spzx.product.api.domain.vo.SkuStockVo;
import com.spzx.product.api.service.RemoteProductSkuService;
import com.spzx.user.api.domain.UserBrowseHistory;
import com.spzx.user.api.service.RemoteUserBrowseHistoryService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Service
public class ItemVoServiceImpl implements ItemVoService {

    @Autowired
    private RemoteProductSkuService remoteProductSkuService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RemoteUserBrowseHistoryService remoteUserBrowseHistoryService;

    @Override
    public ItemVo getItemVoBySkuId(Long skuId) {
        //获取布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("sku:bloom:filter");
        if (!bloomFilter.contains(skuId)) {
            throw new ServiceException("该商品不存在");
        }

        //创建一个ItemVo对象
        ItemVo itemVo = new ItemVo();

        //1根据skuId获取productSku信息
        CompletableFuture<ProductSku> productSkuFuture = CompletableFuture.supplyAsync(() -> {
            //获取Sku信息
            R<ProductSku> productSkuById = remoteProductSkuService.getProductSkuById(skuId, SecurityConstants.INNER);
            //判断是否有值
            if (R.FAIL ==productSkuById.getCode()) {
                throw new ServiceException(productSkuById.getMsg());
            }
            ProductSku productSku = productSkuById.getData();
            //给ItemVo设置值
            itemVo.setProductSku(productSku);
            return productSku;
        }, threadPoolExecutor);

        //1.1根据根据productId获取product信息
        CompletableFuture<Void> productFuture = productSkuFuture.thenAcceptAsync(productSku -> {
            //获取商品信息
            R<Product> productById = remoteProductSkuService.getProductById(productSku.getProductId(), SecurityConstants.INNER);
            //判断
            if (R.FAIL ==productById.getCode()) {
                throw new ServiceException(productById.getMsg());
            }
            Product product = productById.getData();
            //设置值
            itemVo.setProduct(product);

            //获取商品轮播图
            String sliderUrls = product.getSliderUrls();
            //将字符串转换成集合
            String[] split = sliderUrls.split(",");
            List<String> urlList = Arrays.asList(split);
            itemVo.setSliderUrlList(urlList);

            //获取商品规格
            String specValue = product.getSpecValue();
            JSONArray jsonArray = JSON.parseArray(specValue);
            itemVo.setSpecValueList(jsonArray);

        }, threadPoolExecutor);

        //1.2根据productId获取商品详情图片
        CompletableFuture<Void> productDetailsFuture = productSkuFuture.thenAcceptAsync(productSku -> {

            //获取图片详情
            R<ProductDetails> productDetails = remoteProductSkuService.getProductDetails(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL ==productDetails.getCode()) {
                throw new ServiceException(productDetails.getMsg());
            }
            String[] details = productDetails.getData().getImageUrls().split(",");
            List<String> detailList = Arrays.asList(details);
            itemVo.setDetailsImageUrlList(detailList);
        }, threadPoolExecutor);

        //1.3根据商品Id获取商品规格与SkuId
        CompletableFuture<Void> skuSpecValueFuture = productSkuFuture.thenAcceptAsync(productSku -> {
            R<Map<String, Long>> skuSpecValue = remoteProductSkuService.getSkuSpecValue(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == skuSpecValue.getCode()) {
                throw new ServiceException(skuSpecValue.getMsg());
            }
//            itemVo.setSpecValueList(JSON.parseArray(product.getSpecValue()));
            itemVo.setSkuSpecValueMap(skuSpecValue.getData());
        }, threadPoolExecutor);

        //2根据skuId查看商品价格
        CompletableFuture<Void> skuPriceFuture = CompletableFuture.runAsync(() -> {
            //获取最新价格信息
            R<SkuPriceVo> skuPriceVoBySkuId = remoteProductSkuService.getSkuPriceVoBySkuId(skuId, SecurityConstants.INNER);
            if (R.FAIL ==skuPriceVoBySkuId.getCode()) {
                throw new ServiceException(skuPriceVoBySkuId.getMsg());
            }
            itemVo.setSkuPrice(skuPriceVoBySkuId.getData());
        }, threadPoolExecutor);

        //根据skuId查看库存信息
        CompletableFuture<Void> skuStockFuture = CompletableFuture.runAsync(() -> {

            //获取商品库存
            R<SkuStockVo> skuStock = remoteProductSkuService.getSkuStock(skuId, SecurityConstants.INNER);
            if (R.FAIL ==skuStock.getCode()) {
                throw new ServiceException(skuStock.getMsg());
            }
            itemVo.setSkuStockVo(skuStock.getData());

        }, threadPoolExecutor);

        CompletableFuture.allOf(
                productSkuFuture,
                productFuture,
                skuSpecValueFuture,
                productDetailsFuture,
                skuPriceFuture,
                skuStockFuture
                ).join();//阻塞，等到6个任务都完成之后再执行后续内容
        //获取token
        String token = SecurityUtils.getToken();
        //根据token获取用户id
        String userId = JwtUtils.getUserId(token);
        if (StringUtils.hasText(userId)){
            //创建UserBrowseHistory对象
            UserBrowseHistory userBrowseHistory = new UserBrowseHistory();
            //设置用户id
            userBrowseHistory.setUserId(Long.parseLong(userId));
            //设置商品id
            userBrowseHistory.setSkuId(skuId);
            //远程调用用户微服务保存浏览记录
            remoteUserBrowseHistoryService.saveUserBrowseHistory(userBrowseHistory,SecurityConstants.INNER);
        }



        return itemVo;
    }
}
